package com.example.kotlindemo.flow

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.example.kotlindemo.ui.theme.KotlinDemoTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch

class MianActivity: ComponentActivity() {
    private val viewModel:TestFlowViewModel by viewModels()

    private lateinit var flow1:SharedFlow<Int>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            KotlinDemoTheme {
//                Box(modifier = )

            }
        }

        flow1 = mutableListOf(1,2,3,4).asFlow().shareIn(this, SharingStarted.Eagerly, replay = 4)

        lifecycleScope.launch {
            viewModel.state.collect{
                println("$it")
                if(it>6){

                }
            }
        }



        viewModel.download()
    }

}

class TestFlowViewModel:ViewModel(){
    private val _state:MutableStateFlow<Int> = MutableStateFlow(0)
    val state:StateFlow<Int> get() = _state

    fun download(){
        for (state in 0..5){
            viewModelScope.launch{
                delay(200L*state)
                _state.value = state
            }
        }
    }

}